<template>
  <div id="orderSearchDiv">
    <div id="form1" style="">
      <el-form :inline="true" :model="formInline" class="demo-form-inline" @keyup.enter.native="search()"
        id="orderSearchForm">
        <div class="toptitle">
          <el-form-item label="预售活动">
            <br />
            <br />
            <el-select v-model="formInline.activityId" placeholder="请选择" filterable clearable>
              <el-option v-for="(item, i) in activityIdList" :key="i" :value="item.uuid"
                :label="item.activityName"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="订单编号">
            <br />
            <br />
            <el-input v-model="formInline.orderNo" placeholder></el-input>
          </el-form-item>
          <el-form-item label="门店授权码">
            <br />
            <br />
            <el-input v-model="formInline.authCode" placeholder></el-input>
          </el-form-item>

          <el-form-item label="　退货状态">
            <br />
            <br />
            <el-select v-model="formInline.returnStatus" placeholder="请选择" clearable
              @change="getreturnStatus(formInline.returnStatus)">
              <el-option v-for="(item, i) in returnStatusList" :key="i" :value="item.id" :label="item.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属门店">
            <br />
            <br />
            <el-input v-model="formInline.storeName" placeholder></el-input>
          </el-form-item>
        </div>

        <div class="toptitle">
          <!-- <el-form-item label="店主姓名">
            <br> <br>
            <el-input
              v-model="formInline.shopOwnerName"
              placeholder
            ></el-input>
          </el-form-item> -->
          <el-form-item label="所属大区">
            <br />
            <br />
            <el-select v-model="formInline.upOrgSeq">
              <el-option v-for="item in warzoneList" :key="item.orgSeq" :label="item.orgName"
                :value="item.orgSeq"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="会员姓名">
            <br />
            <br />
            <el-input v-model="formInline.memberName" placeholder></el-input>
          </el-form-item>
          <el-form-item label="买家手机号码">
            <br />
            <br />
            <el-input v-model="formInline.tel" placeholder></el-input>
          </el-form-item>

          <el-form-item label="订单状态">
            <br />
            <br />
            <el-select v-model="formInline.orderStatus" placeholder="请选择" clearable>
              <el-option v-for="(item, i) in orderStatusList" :key="i" :value="item.id" :label="item.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="付款日期">
            <br />
            <br />
            <el-date-picker v-model="formInline.payDateRange" type="daterange" align="right" style="width:210px"
              unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
              value-format="yyyy-MM-dd" :picker-options="pickerOptions"></el-date-picker>
          </el-form-item>
        </div>

        <div class="single-box">
          <el-form-item label="预售活动类型">
            <br />
            <br />
            <el-select v-model="formInline.preSaleType" clearable>
              <el-option label="全部" value="" />
              <el-option label="全款预售" value="1" />
              <el-option label="全款预售" value="2" />
            </el-select>
          </el-form-item>

          <el-form-item label="订单客户编号">
            <br />
            <br />
            <el-input v-model="formInline.orderCustomerCode" placeholder></el-input>
          </el-form-item>

          <!-- <el-form-item label="优购订单">
            <br />
            <br />
            <el-select v-model="formInline.isYougouOrder" clearable>
              <el-option label="全部" value="" />
              <el-option label="是" value="1" />
              <el-option label="否" value="0" />
            </el-select>
          </el-form-item> -->
        </div>

        <!-- <div
          class="toptitle"
          style="display: flex;
        margin-left: 3.5%;
    justify-content: flex-start;"
        >

          
  </div> -->
      </el-form>
    </div>
    <div id="multiBtnDiv" style="display:block;text-align:right;margin:20px 0">
      <!-- <el-button
          @click="isActive = !isActive"
          type="primary"
          size="mini"
          v-if="!isActive"
        >筛选条件展开</el-button>
          <el-button
            @click="isActive = !isActive"
            type="primary"
            size="mini"
            v-if="isActive"
          >筛选条件折叠</el-button> -->
      <el-button type="success" size="mini" @click="exportExcel()" icon="el-icon-download">导出</el-button>
      <el-button type="primary" @click="search()" size="mini" icon="el-icon-search">查询</el-button>
      <el-button type="primary" @click="qingkong()" size="mini" icon="el-icon-delete">清空</el-button>
    </div>
    <div id="dataViewDiv">
      <div style="margin:20px 0;">
        <div id="order_total_flex">
          <div class="total_row_item">
            <div class="order_content">
              <div class="order_total_title">订单总数（笔）</div>
              <div class="order_total_info">
                <span class="order_data">{{ totalData.orderNum }}</span>
              </div>
            </div>
          </div>
          <div class="total_row_item">
            <div class="order_content">
              <div class="order_total_title">总金额（元）</div>
              <div class="order_total_info">
                <span class="order_data">{{ totalData.orderMoney }}</span>
              </div>
            </div>
          </div>
          <div class="total_row_item">
            <div class="order_content">
              <div class="order_total_title">未付款单数（笔）</div>
              <div class="order_total_info">
                <span class="order_data">{{ totalData.noPayNum }}</span>
              </div>
            </div>
          </div>
          <div class="total_row_item">
            <div class="order_content">
              <div class="order_total_title">未付款金额（元）</div>
              <div class="order_total_info">
                <span class="order_data">{{ totalData.noPayMoney }}</span>
              </div>
            </div>
          </div>
          <div class="total_row_item">
            <div class="order_content">
              <div class="order_total_title">付款单数（笔）</div>
              <div class="order_total_info">
                <span class="order_data">{{ totalData.payNum }}</span>
              </div>
            </div>
          </div>

          <div class="total_row_item">
            <div class="order_content">
              <div class="order_total_title">付款金额（元）</div>
              <div class="order_total_info">
                <span class="order_data">{{ totalData.payMoney }}</span>
              </div>
            </div>
          </div>

          <div class="total_row_item">
            <div class="order_content">
              <div class="order_total_title">退款单数（笔）</div>
              <div class="order_total_info">
                <span class="order_data">{{ totalData.returnNum }}</span>
              </div>
            </div>
          </div>

          <div class="total_row_item">
            <div class="order_content">
              <div class="order_total_title">退款金额（元）</div>
              <div class="order_total_info">
                <span class="order_data">{{ totalData.returnMoney }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="table1">
      <el-table id="rebateSetTable" ref="table1" height="500px" key="table1" tooltip-effect="dark" v-loading="loading"
        :data="tableData" border :header-cell-style="{ background: '#eef1f6', color: '#606266' }">
        <el-table-column type="index" label="序号" align="center" width="60"></el-table-column>

        <el-table-column prop="orderNo" label="订单编号" align="center" width="200"></el-table-column>

        <el-table-column prop="memberName" label="会员姓名" align="center" show-overflow-tooltip></el-table-column>

        <el-table-column prop="upOrgZone" label="所属大区" align="center" show-overflow-tooltip></el-table-column>

        <el-table-column prop="orgName" label="门店名称" align="left" show-overflow-tooltip></el-table-column>
        <el-table-column prop="authCode" label="门店授权码" align="center" show-overflow-tooltip></el-table-column>
        >
        <el-table-column prop="tel" label="买家手机号码" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column prop="totalAmount" label="总数量" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column prop="receivedMoney" label="实收金额" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column prop="orderCustomerCode" label="订单客户编号" align="center" :min-width="200"></el-table-column>
        <el-table-column prop="returnStatus" label="订单退货状态" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="scope.row.returnStatus === 0">正常单</span>
            <span v-if="scope.row.returnStatus === 1">被退单</span>
          </template>
        </el-table-column>

        <el-table-column prop="orderStatus" label="订单状态" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="scope.row.orderStatus === 0">待支付</span>
            <span v-if="scope.row.orderStatus === 1">待发货</span>
            <span v-if="scope.row.orderStatus === 2">待收货</span>
            <span v-if="scope.row.orderStatus === 3">已完成</span>
            <span v-if="scope.row.orderStatus === 4">已取消</span>
          </template>
        </el-table-column>
        <el-table-column prop="orderDate" label="订单日期" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" @click="showOrderDetail(scope.row)" type="text">查看</el-button>
            <el-button v-if="isShowSyncOrder" @click="syncOrder(scope.row)" type="text" size="mini">同步订单</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-form :inline="true" :model="formInline">
        <el-form-item style="margin-top: 0px;"></el-form-item>
      </el-form>
      <div class="block" style="margin-top:-22px">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :disabled="dindanflag"
          :page-sizes="[10, 20, 30, 50, 100, 150, 200]" :current-page="listQuery.current" :page-size="listQuery.size"
          layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
      </div>
    </div>

    <!--列表配置-->
  </div>
</template>

<script>
// import Sortable from "sortablejs";
// import { getmemberrule } from "@/api/membergrade";
// import collapse from "@/utils/collapse.js";
import {
  queryPresaleOrderTotal,
  queryPresaleOrderList,
  toExcelQueryPresaleOrder,
} from '@/api/presaleOrderSearch';
import { getWarzoneList } from '@/api/preSaleActivity';
import { queryPreSaleActList } from '@/api/preSaleActivity';
import { onlinePayQuery } from '@/api/tradeOrderSearch';
import qs from 'qs';
import FileSaver from 'file-saver';
import XLSX from 'xlsx';

const curDateStr = function () {
  var curDate = new Date();
  var year = curDate.getFullYear();
  var month = curDate.getMonth() + 1;
  month = month > 9 ? month : '0' + month;
  var date = curDate.getDate();
  date = date > 9 ? date : '0' + date;
  return year + '-' + month + '-' + date;
};
export default {
  data() {
    return {
      logininfo: '',
      orgSeq: '',
      dindanflag: false,
      dindanflagone: false,
      orgType: '',
      loading: false,
      exportLoading: false,
      warzoneList: [],
      insertLoading: false,
      goodsPicDialoVisible: false,
      activityIdList: [],
      isActive: true,
      dialogVisibleImg: false,
      dialogImageUrl: '',
      picList: [],
      dataViewDate: '1',
      dataViewRange: '',
      totalData: {
        orderNum: 0,
        orderMoney: 0,
        noPayNum: 0,
        noPayMoney: 0,
        payNum: 0,
        payMoney: 0,
        returnNum: 0,
        returnMoney: 0,
      },
      orderStatusList: [
        {
          id: '0',
          name: '待支付',
        },
        {
          id: '1',
          name: '待发货',
        },
        {
          id: '2',
          name: '待收货',
        },
        {
          id: '3',
          name: '已完成',
        },
        {
          id: '-1',
          name: '已退款',
        },
      ], //订单状态
      returnStatusList: [
        {
          id: '',
          name: '全部',
        },

        {
          id: '0',
          name: '正常单',
        },
        {
          id: '1',
          name: '被退单',
        },
      ], //退货状态
      payMethodList: [
        {
          id: '0',
          name: '云店线下',
        },
        {
          id: '1',
          name: '线上支付',
        },
        {
          id: '2',
          name: 'pos线下支付',
        },
        {
          id: '3',
          name: '微信',
        },
        {
          id: '4',
          name: '支付宝',
        },
        {
          id: '5',
          name: '银行卡',
        },
      ],
      deliveryMethodList: [
        {
          id: '1',
          name: '门店自提',
        },
        {
          id: '2',
          name: '配送服务',
        },
        {
          id: '3',
          name: '快递服务',
        },
      ], //配送方式
      gradelevelOptions: [], //会员等级
      formInline: {
        activityId: '',
        upOrgSeq: '',
        payDateRange: [],
        upOrgSeq: '',
        memberName: '',
        storeName: '',
        authCode: '',
        orderStatus: '',
        returnStatus: '',
        orderNo: '',
        tel: '',
        preSaleType: '',
        isYougouOrder: '',
        orderCustomerCode: '',
      },
      allCol: [],
      col: [],
      dropCol: [],
      expandRowKeys: [],
      tableData: [], //订单列表数据
      tableDataExcel: [], //导出数据
      payData: [], //支付列表数据
      itemData: [], //商品列表数据
      total: 0,
      listQuery: {
        current: 1,
        size: 100,
      },
      sort: '',
      order: '',
      configTableDialogVisible: false, //列表配置弹窗状态
      formInline2: {
        isIndeterminate: false, //是否半选中
        isAll: true, //是否全部显示,
        menuCode: 'normalOrderSearch',
      },
      userMenuFieldList: [], //全部列名列表
      userMenuAllFields: [], //全部的列名
      userMenuShowFields: [], //显示的列名
      userOldMenuShowFields: [], //原显示的列名
      pickerOptions: {},

      isShowSyncOrder: false,
    };
  },

  mounted() {
    const logininfo = localStorage.getItem('logininfo');
    const logininfoJson = logininfo ? JSON.parse(logininfo) : {};
    const userName = logininfoJson.userName ? logininfoJson.userName : '';
    const userType = logininfoJson.userType ? logininfoJson.userType : '';
    if (this.$route.query.username == 'lzq' || (userName == 'lzq' && userType == '1')) {
      this.isShowSyncOrder = true;
    }

    this.queryPreSaleActList();

    this.getWarzoneList();
  },
  filters: {
    numFilter(value) {
      let realVal = '';
      if (!isNaN(value) && value !== '') {
        // 截取当前数据到小数点后2位
        realVal = parseFloat(value).toFixed(2);
      } else {
        realVal = '--';
      }
      return realVal;
    },
  },
  methods: {
    getreturnStatus(v) {
      console.log(v);
      if (v == '1') {
        this.formInline.orderStatus = '3';
        console.log(this.formInline.orderStatus);
      }
    },
    getWarzoneList() {
      let data = {};
      getWarzoneList(data).then((res) => {
        this.warzoneList = res.records;
      });
    },
    queryPreSaleActList() {
      let data = {
        size: '100000',
        current: this.listQuery.current,
        condition: {},
        ascs: [],
        descs: [],
      };
      queryPreSaleActList(data).then((res) => {
        this.activityIdList = res.records;
        if (res.records.length == 0) {
        } else {
          (this.formInline.activityId = this.activityIdList[0].uuid),
            this.queryPresaleOrderList();
        }
      });
    },

    //拖拽列表
    columnDrop() {
      const wrapperTr = document.querySelector('.el-table__header-wrapper tr');
      this.sortable = Sortable.create(wrapperTr, {
        animation: 180,
        delay: 0,
        onEnd: (evt) => {
          const oldItem = this.dropCol[evt.oldIndex - 1];
          this.dropCol.splice(evt.oldIndex - 1, 1);
          this.dropCol.splice(evt.newIndex - 1, 0, oldItem);
        },
      });
    },

    /*订单列表*/
    queryPresaleOrderList() {
      let payBeginDate = '';
      let payEndDate = '';
      if (
        this.formInline.payDateRange != null &&
        this.formInline.payDateRange.length == 2
      ) {
        payBeginDate = this.formInline.payDateRange[0];
        payEndDate = this.formInline.payDateRange[1];
      } else {
        this.formInline.payDateRange = '';
      }

      let data = {
        current: this.listQuery.current,
        size: this.listQuery.size,
        condition: {
          activityId: this.formInline.activityId,
          payBeginDate: payBeginDate,
          payEndDate: payEndDate,
          upOrgSeq: this.formInline.upOrgSeq,
          memberName: this.formInline.memberName.trim(),
          storeName: this.formInline.storeName.trim(),
          authCode: this.formInline.authCode.trim(),
          orderStatus: this.formInline.orderStatus,
          returnStatus: this.formInline.returnStatus,
          orderNo: this.formInline.orderNo.trim(),
          tel: this.formInline.tel,
          /*  end */
        },
        ascs: [],
        descs: [],
      };
      let dataone = {
        // current: this.listQuery.current,
        // size: this.listQuery.size,
        // condition: {
        activityId: this.formInline.activityId,
        payBeginDate: payBeginDate,
        payEndDate: payEndDate,
        upOrgSeq: this.formInline.upOrgSeq,
        memberName: this.formInline.memberName.trim(),
        storeName: this.formInline.storeName.trim(),
        authCode: this.formInline.authCode.trim(),
        orderStatus: this.formInline.orderStatus,
        returnStatus: this.formInline.returnStatus,
        orderNo: this.formInline.orderNo.trim(),
        tel: this.formInline.tel,
        /*  end */
        // },
        // ascs: [],
        // descs: []
      };
      queryPresaleOrderList(data).then((res) => {
        // this.dindanflag = false;
        // this.dindanflagone = false;
        this.loading = false;
        this.tableData = res.records;
        this.total = res.total;
        queryPresaleOrderTotal(dataone).then((res) => {
          this.loading = false;
          (this.totalData.orderNum = res.result.orderNum),
            (this.totalData.orderMoney = res.result.orderMoney),
            (this.totalData.noPayNum = res.result.noPayNum),
            (this.totalData.noPayMoney = res.result.noPayMoney),
            (this.totalData.payNum = res.result.payNum),
            (this.totalData.payMoney = res.result.payMoney),
            (this.totalData.returnNum = res.result.returnNum),
            (this.totalData.returnMoney = res.result.returnMoney);
        });
      });
    },
    handleSizeChange(val) {
      this.listQuery.size = val;

      this.queryPresaleOrderList();
    },
    handleCurrentChange(val) {
      this.listQuery.current = val;
      this.dindanflag = true;
      this.queryPresaleOrderList();
    },
    //查询
    search() {
      this.listQuery.current = 1;
      this.dindanflagone = true;
      this.queryPresaleOrderList();
    },
    //清空
    qingkong() {
      (this.formInline.activityId = ''),
        (this.formInline.payBeginDate = []),
        (this.formInline.memberName = ''),
        (this.formInline.storeName = ''),
        (this.formInline.authCode = ''),
        (this.formInline.orderStatus = ''),
        (this.formInline.returnStatus = ''),
        (this.formInline.orderNo = ''),
        (this.formInline.tel = '');
      this.formInline.upOrgSeq = '';
      this.formInline.preSaleType = '';
      this.formInline.isYougouOrder = '';
      this.queryPresaleOrderList();
    },

    //数字格式化
    fixData(row, column, cellValue, index) {
      if (cellValue != null && !isNaN(cellValue)) {
        if (cellValue < 0) {
          return '0.00';
        } else {
          return cellValue.toFixed(2);
        }
      } else {
        return cellValue;
      }
    },
    //查看订单详情（跳转）
    showOrderDetail(v) {
      // let orderSearchParam = {
      //   formInline: this.formInline,
      //   listQuery: this.listQuery,
      //   total: this.total
      // };
      // sessionStorage.setItem("pageFrom", "preSaleOrderSearch");
      // sessionStorage.setItem(
      //   "orderSearchParam",
      //   JSON.stringify(orderSearchParam)
      // );
      this.$router.push({
        name: 'preSaleOrderSearchDetail',
        params: {
          edit: v,
        },
      });
    },

    // 导出
    exportExcel() {
      let payBeginDate = '';
      let payEndDate = '';
      if (
        this.formInline.payDateRange != null &&
        this.formInline.payDateRange.length == 2
      ) {
        payBeginDate = this.formInline.payDateRange[0];
        payEndDate = this.formInline.payDateRange[1];
      } else {
        this.formInline.payDateRange = '';
      }
      toExcelQueryPresaleOrder({
        condition: {
          activityId: this.formInline.activityId,
          payBeginDate: payBeginDate,
          payEndDate: payEndDate,
          upOrgSeq: this.formInline.upOrgSeq,
          memberName: this.formInline.memberName.trim(),
          storeName: this.formInline.storeName.trim(),
          authCode: this.formInline.authCode.trim(),
          orderStatus: this.formInline.orderStatus,
          returnStatus: this.formInline.returnStatus,
          orderNo: this.formInline.orderNo.trim(),
          tel: this.formInline.tel,
        },
      })
        .then((res) => {
          const link = document.createElement('a');
          let blob = new Blob([res], {
            type: 'application/vnd.ms-excel',
          });
          link.style.display = 'none';
          //设置连接
          link.href = URL.createObjectURL(blob);
          link.download = '预售活动列表.xlsx';
          document.body.appendChild(link);
          //模拟点击事件
          link.click();
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 订单同步
    syncOrder(detail) {
      onlinePayQuery({
        orderId: detail.uuid,
        isSystemOperate: 1,
        orderPresaleType: 3,
      }).then(res => {
        if (res.code) {
          this.$message.success(res.message);
          this.queryPresaleOrderList();
        } else {
          this.$message.error(res.message);
        }
      })
    }
  },
  //其他
  computed: {},
};
</script>
<style scoped>
.el-form--inline /deep/ .el-form-item {
  display: flex;
  align-items: flex-start;
  flex-direction: column;
}

.el-form-item /deep/ .el-form-item__content {
  line-height: 10px !important;
}

.toptitle {
  display: flex;
  justify-content: space-around;
}

#orderSearchDiv /deep/ .el-radio-button-inner-datepicker .el-radio-button__inner {
  padding: 0;
}

#orderSearchDiv /deep/ .el-radio-button-inner-datepicker .el-input__inner {
  border: none;
  height: 38px;
}

#orderSearchDiv /deep/ .el-form--inline .el-form-item__content {
  width: 180px;
}

#orderSearchDiv /deep/ .el-range-editor.el-input__inner {
  width: 250px;
}

#orderSearchDiv /deep/ .el-dialog__body {
  padding-top: 0;
}

#order_total_flex {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: space-around;
}

#order_total_flex /deep/ .order_content {
  cursor: pointer;
  /* width: 200px; */
  padding: 20px;
  margin: 0 auto;
  text-align: center;
  overflow: hidden;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
}

#order_total_flex /deep/ .order_detail {
  width: 200px;
  margin-top: 10px;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: space-between;
}

#order_total_flex /deep/ .order_content2 {
  width: 60px;
  cursor: pointer;
  padding: 10px 0;
  margin: 0 1px;
  text-align: center;
  overflow: hidden;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
}

#order_total_flex /deep/ .order_content .order_total_title {
  color: #000;
}

#order_total_flex /deep/ .order_content .order_total_info {
  margin-top: 10px;
}

#order_total_flex /deep/ .order_content .order_data {
  font-size: 1.4em;
  font-weight: bold;
}

#configTableDiv /deep/ .el-divider--horizontal {
  margin-top: 0;
}

.line_line {
  border-left: 5px solid #dddddd;
  display: inline-block;
  height: 6.25rem;
  margin-left: -1px;
  padding: 0px 0px 0px 3px;
}

.single-box {
  display: flex;
}

.single-box /deep/ .el-form-item {
  margin-left: 58px;
}

.single-box /deep/ .el-form-item:last-child {
  margin-left: 116px;
}
</style>
